package com.work.yshop.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.work.yshop.R;
import com.work.yshop.provider.ProductProvider;
import com.work.yshop.utils.ImageUtils;
import com.work.yshop.utils.UserSession;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 商品发布页面
 */
public class PublishProductActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_PICK = 100;
    
    private ImageView btnBack;
    private TextView btnPublish;
    private CardView cardImageUpload;
    private ImageView ivProductImage;
    private EditText etProductName;
    private Spinner spinnerCategory;
    private EditText etPrice;
    private EditText etStock;
    private EditText etDescription;
    private Button btnSubmit;
    
    private String[] categories = {"水果", "蔬菜", "肉禽蛋", "水产", "干货", "粮油", "其他"};
    private String imageUrl = ""; // 存储图片路径
    private boolean isImageSelected = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_product);
        
        initViews();
        setupSpinner();
        setupListeners();
    }
    
    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        btnPublish = findViewById(R.id.btn_publish);
        cardImageUpload = findViewById(R.id.card_image_upload);
        ivProductImage = findViewById(R.id.iv_product_image);
        etProductName = findViewById(R.id.et_product_name);
        spinnerCategory = findViewById(R.id.spinner_category);
        etPrice = findViewById(R.id.et_price);
        etStock = findViewById(R.id.et_stock);
        etDescription = findViewById(R.id.et_description);
        btnSubmit = findViewById(R.id.btn_submit);
    }
    
    private void setupSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(adapter);
    }
    
    private void setupListeners() {
        btnBack.setOnClickListener(v -> onBackPressed());
        
        btnPublish.setOnClickListener(v -> publishProduct());
        
        cardImageUpload.setOnClickListener(v -> {
            // 启动图片选择
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_IMAGE_PICK);
        });
        
        btnSubmit.setOnClickListener(v -> publishProduct());
    }
    
    private void publishProduct() {
        // 验证输入
        String name = etProductName.getText().toString().trim();
        String priceStr = etPrice.getText().toString().trim();
        String stockStr = etStock.getText().toString().trim();
        String description = etDescription.getText().toString().trim();
        String category = spinnerCategory.getSelectedItem().toString();
        
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入商品名称", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (TextUtils.isEmpty(priceStr)) {
            Toast.makeText(this, "请输入商品价格", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (TextUtils.isEmpty(stockStr)) {
            Toast.makeText(this, "请输入商品库存", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!isImageSelected) {
            Toast.makeText(this, "请选择商品图片", Toast.LENGTH_SHORT).show();
            return;
        }
        
        double price;
        int stock;
        
        try {
            price = Double.parseDouble(priceStr);
            stock = Integer.parseInt(stockStr);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的价格和库存", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (price <= 0) {
            Toast.makeText(this, "价格必须大于0", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (stock <= 0) {
            Toast.makeText(this, "库存必须大于0", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建商品数据
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("price", price);
        values.put("stock", stock);
        values.put("description", description);
        values.put("category", category);
        values.put("image_url", imageUrl);
        values.put("status", 1); // 1表示已上架，0表示已下架
        
        // 设置卖家ID
        int sellerId = UserSession.getInstance().getUserId();
        values.put("seller_id", sellerId);
        
        // 设置原价（默认比售价高20%）
        double originalPrice = price * 1.2;
        values.put("original_price", originalPrice);
        
        // 设置单位（默认为"件"）
        values.put("unit", "件");
        
        // 设置销量（默认为0）
        values.put("sales_count", 0);
        
        // 设置发布时间和更新时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String currentTime = sdf.format(new Date());
        values.put("publish_date", currentTime);
        values.put("update_date", currentTime);
        
        // 插入数据到ContentProvider
        Uri uri = getContentResolver().insert(ProductProvider.CONTENT_URI, values);
        
        if (uri != null) {
            Toast.makeText(this, "商品发布成功", Toast.LENGTH_SHORT).show();
            setResult(RESULT_OK);
            finish();
        } else {
            Toast.makeText(this, "商品发布失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                // 显示选择的图片
                ivProductImage.setImageURI(selectedImageUri);
                
                // 获取图片路径
                imageUrl = ImageUtils.getPathFromUri(this, selectedImageUri);
                isImageSelected = true;
            }
        }
    }
} 